package br.com.tartarugasindomaveis.ti.app;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class PicasaService {

	public String page = "";

	public List<Album> carregaImagens(String urlPicasa) {
		BufferedReader in = null;

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(urlPicasa));
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));

			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			page = sb.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}

		// http://developer.android.com/reference/org/json/JSONTokener.html

		String json = page;

		JSONObject object;

		String miniatura = "";
		String foto = "";
		List<Album> listaAlbum = new ArrayList<Album>();

		try {
			object = (JSONObject) new JSONTokener(json).nextValue();
			JSONObject feed = object.getJSONObject("feed");
			JSONArray entry = feed.getJSONArray("entry");

			for (int i = 0; i < entry.length(); ++i) {
				JSONObject rec = entry.getJSONObject(i);
				JSONObject group = rec.getJSONObject("media$group");

				// JSONArray content = group.getJSONArray("media$content");
				// JSONObject fotoUrl = content.getJSONObject(0);
				// foto = fotoUrl.getString("url");

				JSONArray content = group.getJSONArray("media$thumbnail");
				JSONObject fotoUrl = content.getJSONObject(2);
				foto = fotoUrl.getString("url");

				JSONArray thumbnail = group.getJSONArray("media$thumbnail");
				JSONObject miniaturaUrl = thumbnail.getJSONObject(0);
				miniatura = miniaturaUrl.getString("url");

				Album album = new Album(foto, miniatura);
				listaAlbum.add(album);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		return listaAlbum;

	}

	public List<Album> carregaImagensTeste() {

		String miniatura = "";
		String foto = "";
		List<Album> listaAlbum = new ArrayList<Album>();

		// *******************************
		long t0, t1;
		t0 = System.currentTimeMillis();
		do {
			t1 = System.currentTimeMillis();
		} while ((t1 - t0) < (20 * 1000));
		// *****************************

		for (int i = 0; i < 100; ++i) {
			miniatura = "status";
			foto = "Titulo" + i;

			Album album = new Album(foto, miniatura);
			listaAlbum.add(album);
		}

		return listaAlbum;
	}

}
